#!/bin/bash
# Ubuntu 22.04 初始化脚本
# 适用于 VMware 虚拟机，包含常用工具安装和系统配置优化

set -e  # 遇到错误立即退出

main(){
  config_sources_list
  # 常用工具安装
  install_common_tools
}

# amd64 配置国内清华镜像源 参考https://zhuanlan.zhihu.com/p/462237613
config_sources_list(){
  sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak_$(date +%Y%m%d_%H%M%S)

  cat <<EOF | sudo tee /etc/apt/sources.list
# 默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-updates main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-backports main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-backports main restricted universe multiverse

# 以下安全更新软件源包含了官方源与镜像站配置，如有需要可自行修改注释切换
deb http://security.ubuntu.com/ubuntu/ jammy-security main restricted universe multiverse
# deb-src http://security.ubuntu.com/ubuntu/ jammy-security main restricted universe multivers

# 预发布软件源，不建议启用
# deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-proposed main restricted universe multiverse
# # deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-proposed main restricted universe multiverse
EOF

  # 更新软件
  sudo apt-get update -y
  # sudo apt-get upgrade -y
}


# 常用工具安装
install_common_tools() {
    echo "=== 更新系统源 ==="
    #sudo apt-get update -y && sudo apt-get upgrade -y

    echo "=== 安装常用工具 ==="
    sudo apt-get install -y lrzsz gedit bash-completion vim nano \
        net-tools iputils-ping traceroute curl wget git unzip zip \
        build-essential htop tcpdump sysstat netplan.io

    echo "=== 配置 Git 默认信息（如需修改请编辑此处）==="
    git config --global user.name "lushuan"
    git config --global user.email "lushuan2071@126.com"

    echo "=== 配置 vim 默认设置 ==="
    cat <<EOF > ~/.vimrc
set number
syntax on
set tabstop=4
set shiftwidth=4
set expandtab
EOF

    echo "=== 配置 bashrc: 彩色提示符、命令时间、自动补全 ==="
    sed -i 's/#force_color_prompt=yes/force_color_prompt=yes/' ~/.bashrc
    echo 'HISTTIMEFORMAT="%F %T "' >> ~/.bashrc
    echo "if [ -f /etc/bash_completion ]; then" >> ~/.bashrc
    echo "  . /etc/bash_completion" >> ~/.bashrc
    echo "fi" >> ~/.bashrc
    source ~/.bashrc
    bash
}

# 生产环境服务安装
install_prod_services() {
    echo "=== 安装 Supervisor ==="
    sudo apt-get install -y supervisor
    sudo systemctl enable supervisor
    sudo systemctl start supervisor

    echo "=== 安装 Docker ==="
    sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common
    # 移除掉原来的 docker.list
    sudo rm -f /etc/apt/sources.list.d/docker.list
    sudo rm -f /usr/share/keyrings/docker-ce-archive-keyring.gpg

    # 使用清华镜像源
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-ce-archive-keyring.gpg] \
https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/ubuntu jammy stable" \
| sudo tee /etc/apt/sources.list.d/docker.list

    # 获取清华提供的 GPG key
    curl -fsSL https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/ubuntu/gpg \
      | sudo gpg --dearmor -o /usr/share/keyrings/docker-ce-archive-keyring.gpg

    sudo apt-get update -y
    sudo apt-get install -y docker-ce docker-ce-cli containerd.io
    #sudo apt-get install -y  containerd.io

    sudo systemctl enable docker
    sudo systemctl start docker
}

# 适配不同架构和不同Ubuntu 版本安装docker,Ubuntu 不同版本安装的docker 会识别glibc 版本
install_docker(){

  sources ./install_docker_smart.sh
  bash install_docker_smart.sh

}

# 允许 root 登录
enable_root_login() {
    echo "=== 允许 root 用户远程登录 ==="
    grep PermitRootLogin  /etc/ssh/sshd_config
    sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config
    sudo systemctl restart sshd
}

# 禁用 cloud-init 的网络管理,保留自定义 IP 配置不被覆盖
cloud_init_disable(){
   touch /etc/cloud/cloud-init.disabled
   sudo mkdir -p /etc/cloud/cloud.cfg.d
   echo "network: {config: disabled}" | sudo tee /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg
   # ubuntu 22.04
   mv /etc/netplan/*.yaml /opt

   sudo touch /etc/netplan/01-netcfg.yaml
   # 对应ip、网关、域名需要手动修改一下
  cat > /etc/netplan/01-netcfg.yaml << EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    ens32:
      dhcp4: no
      addresses: [192.168.4.251/24]
      gateway4: 192.168.4.1
      nameservers:
        addresses: [223.5.5.5, 8.8.8.8, 114.114.114.114]
EOF
  cat /etc/netplan/01-netcfg.yaml

  netplan try
  netplan apply


}






# containerd 设置为中科大镜像仓库
containerd_config_hub(){

cat > /etc/containerd/config.toml <<EOF
version = 2
[plugins]
[plugins."io.containerd.grpc.v1.cri"]
    disable_apparmor = false
    disable_cgroup = false
    disable_hugetlb_controller = true
    disable_proc_mount = false
    disable_tcp_service = true
    enable_selinux = false
    enable_tls_streaming = false
    ignore_image_defined_volumes = false
    max_concurrent_downloads = 3
    max_container_log_line_size = 16384
    netns_mounts_under_state_dir = false
    restrict_oom_score_adj = false
    sandbox_image = "registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.5"
    selinux_category_range = 1024
    stats_collect_period = 10
    stream_idle_timeout = "4h0m0s"
    stream_server_address = "127.0.0.1"
    stream_server_port = "0"
    systemd_cgroup = false
    tolerate_missing_hugetlb_controller = true
    unset_seccomp_profile = ""

    [plugins."io.containerd.grpc.v1.cri".cni]
      bin_dir = "/opt/cni/bin"
      conf_dir = "/etc/cni/net.d"
      conf_template = ""
      max_conf_num = 1

    [plugins."io.containerd.grpc.v1.cri".containerd]
      default_runtime_name = "runc"
      disable_snapshot_annotations = true
      discard_unpacked_layers = false
      no_pivot = false
      snapshotter = "overlayfs"

      [plugins."io.containerd.grpc.v1.cri".containerd.default_runtime]
        base_runtime_spec = ""
        container_annotations = []
        pod_annotations = []
        privileged_without_host_devices = false
        runtime_engine = ""
        runtime_root = ""
        runtime_type = ""

        [plugins."io.containerd.grpc.v1.cri".containerd.default_runtime.options]

      [plugins."io.containerd.grpc.v1.cri".containerd.runtimes]

        [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc]
          base_runtime_spec = ""
          container_annotations = []
          pod_annotations = []
          privileged_without_host_devices = false
          runtime_engine = ""
          runtime_root = ""
          runtime_type = "io.containerd.runc.v2"

          [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc.options]
            BinaryName = ""
            CriuImagePath = ""
            CriuPath = ""
            CriuWorkPath = ""
            IoGid = 0
            IoUid = 0
            NoNewKeyring = false
            NoPivotRoot = false
            Root = ""
            ShimCgroup = ""
        [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runsc]
          runtime_type = "io.containerd.runsc.v1"

[plugins."io.containerd.grpc.v1.cri".registry.mirrors]
  # 如下这些仓库可以作为公共仓库使用
  [plugins."io.containerd.grpc.v1.cri".registry.mirrors."docker.io"]
      endpoint = ["https://docker.mirrors.ustc.edu.cn","http://hub-mirror.c.163.com"]
  [plugins."io.containerd.grpc.v1.cri".registry.mirrors."gcr.io"]
      endpoint = ["https://gcr.mirrors.ustc.edu.cn"]
  [plugins."io.containerd.grpc.v1.cri".registry.mirrors."k8s.gcr.io"]
      endpoint = ["https://gcr.mirrors.ustc.edu.cn/google-containers/"]
  [plugins."io.containerd.grpc.v1.cri".registry.mirrors."quay.io"]
      endpoint = ["https://quay.mirrors.ustc.edu.cn"]
  # 内部私有仓库配置
  [plugins."io.containerd.grpc.v1.cri".registry.mirrors."www.myharbor.com"]
      endpoint = ["https://www.myharbor.com/"]

EOF

# 启动Containerd
systemctl daemon-reload
systemctl restart containerd

}



ubuntu_config_sources_list_full(){
  cd ; mkdir ubuntu ; cd ubuntu
  docker stop ubuntu
  docker rm ubuntu

  cat > sources.list << EOF
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://archive.ubuntu.com/ubuntu/ focal main restricted
# deb-src http://archive.ubuntu.com/ubuntu/ focal main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://archive.ubuntu.com/ubuntu/ focal-updates main restricted
# deb-src http://archive.ubuntu.com/ubuntu/ focal-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://archive.ubuntu.com/ubuntu/ focal universe
# deb-src http://archive.ubuntu.com/ubuntu/ focal universe
deb http://archive.ubuntu.com/ubuntu/ focal-updates universe
# deb-src http://archive.ubuntu.com/ubuntu/ focal-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://archive.ubuntu.com/ubuntu/ focal multiverse
# deb-src http://archive.ubuntu.com/ubuntu/ focal multiverse
deb http://archive.ubuntu.com/ubuntu/ focal-updates multiverse
# deb-src http://archive.ubuntu.com/ubuntu/ focal-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://archive.ubuntu.com/ubuntu/ focal-backports main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu/ focal-backports main restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu focal partner
# deb-src http://archive.canonical.com/ubuntu focal partner

deb http://security.ubuntu.com/ubuntu/ focal-security main restricted
# deb-src http://security.ubuntu.com/ubuntu/ focal-security main restricted
deb http://security.ubuntu.com/ubuntu/ focal-security universe
# deb-src http://security.ubuntu.com/ubuntu/ focal-security universe
deb http://security.ubuntu.com/ubuntu/ focal-security multiverse
# deb-src http://security.ubuntu.com/ubuntu/ focal-security multiverse

# 腾讯云的镜像源
deb http://mirrors.tencentyun.com/ubuntu/ xenial main restricted universe multiverse
deb http://mirrors.tencentyun.com/ubuntu/ xenial-security main restricted universe multiverse
deb http://mirrors.tencentyun.com/ubuntu/ xenial-updates main restricted universe multiverse
deb-src http://mirrors.tencentyun.com/ubuntu/ xenial main restricted universe multiverse
deb-src http://mirrors.tencentyun.com/ubuntu/ xenial-security main restricted universe multiverse
deb-src http://mirrors.tencentyun.com/ubuntu/ xenial-updates main restricted universe multiverse

# 阿里的镜像源
deb http://mirrors.aliyun.com/ubuntu/ xenial main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse

# 清华大学的镜像源，默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-security main restricted universe multiverse
# deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ bionic-security main restricted universe multiverse

EOF
# 其中，–privileged=true表示赋予这个容器特殊权限，/sbin/init表示初始化系统环境
sudo docker run -itd --name ubuntu  --privileged=true -v $HOME/ubuntu/sources.list:/etc/apt/sources.list  ubuntu:20.04 /sbin/init

}

ubuntu_systemd(){
  # 进入 ubunut 系统
  sudo docker exec -it ubuntu apt-get update
  sudo docker exec -it ubuntu  bash
  apt-get install vim zip -y
  # 选择6 亚洲 70 上海
  apt-get install --reinstall systemd -y
  apt install systemctl  -y
  # 安装ssh
  apt-get install openssh-server openssh-client -y
  /etc/init.d/ssh restart

  #
  mkdir $HOME/systemd;cd $HOME/systemd
  cat > StartupScipt.sh << EOF
#!/bin/sh
# 创建一个临时文件
touch /tmp/1.txt
EOF

  # 赋执行权限
  chmod u+x  $HOME/systemd/StartupScipt.sh
  chmod g+x  $HOME/systemd/StartupScipt.sh
  # 进入 systemd 放置 service 的目录，在该目录下可看到大量服务配置文件，命令如下
  cd /etc/systemd/system
  # 查看文件列表
  ls -al
  # 创建一个.service 启动脚本
  cat > /etc/systemd/system/StartupExample.service << EOF
[Unit]
Description=Startup Example

[Service]
ExecStart=$HOME/systemd/StartupScipt.sh

[Install]
WantedBy=multi-user.target
EOF

  # 手动运行创建service 文件
  # 手动运行 StartupExample.service
  systemctl start StartupExample.service
  # 查看运行日志
  systemctl status StartupExample.service
  # 设置服务为 enable 状态，使之能开机运行
  systemctl enable StartupExample.service

  # 查看文件是否创建成功
  ls -al /tmp
}





main